package com.aliyun.messagemgt.web.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.aliyun.messagemgt.application.service.BaseReceiveGroupService;
import com.aliyun.messagemgt.application.service.MsgSourceService;
import com.aliyun.messagemgt.application.service.excel.ImportExcelService;
import com.aliyun.messagemgt.application.service.excel.OutputExcelService;
import com.aliyun.messagemgt.common.enums.ChannelTypeEnum;
import com.aliyun.messagemgt.common.dto.response.ResultMap;
import com.aliyun.messagemgt.dto.PushChannelDto;
import com.aliyun.messagemgt.dto.base.BaseReceiveGroupDetailDTO;
import com.aliyun.messagemgt.dto.base.BaseReceiveGroupQry;
import com.aliyun.messagemgt.dto.base.BaseReceiveGroupRangeDTO;
import com.aliyun.messagemgt.dto.excel.BaseMessageSourceExcel;
import com.aliyun.messagemgt.dto.excel.BaseReceiveGroupDetailExcel;
import com.aliyun.messagemgt.dto.excel.MessageTemplateExcel;
import com.aliyun.messagemgt.dto.excel.MsgSourceExcel;
import com.aliyun.messagemgt.dto.query.MsgQuery;
import com.aliyun.messagemgt.dto.vo.MsgSourceVO;
import com.aliyun.messagemgt.excel.ExcelReaderUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(tags = "excel导入导出相关接口")
@CrossOrigin
@RestController
@RequestMapping("/excel")
@Slf4j
public class ExcelExcutorController {

    @Autowired
    private ImportExcelService importExcelService;

    @Autowired
    private OutputExcelService outputExcelService;

    //接受组
    @Autowired
    private BaseReceiveGroupService baseReceiveGroupService;

    //任务配置
    @Autowired
    private MsgSourceService msgSourceService;

    @RequestMapping(value = "/importMessageTemplateExcel", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "导入消息模板", httpMethod = "POST", notes = "导入消息模板")
    public ResultMap importMessageTemplateExcel(@RequestParam("excel") MultipartFile multipartFile, @RequestParam("tenantCode") String tenantCode) {
        ResultMap resultMap = new ResultMap();
        if (multipartFile == null || tenantCode == null) {
            resultMap.setErrCode(1);
            resultMap.setErrMsg("文件和tenantCode不可以为null");
            return resultMap;
        }
        ExcelReaderUtil<MessageTemplateExcel> excelReader = new ExcelReaderUtil<>(MessageTemplateExcel.class);
        List<MessageTemplateExcel> modelList;
        try {
            InputStream inputStream = multipartFile.getInputStream();
            modelList = excelReader.readByStream(inputStream);
            //设置场景
            for (MessageTemplateExcel messageTemplateExcel : modelList) {
                if (messageTemplateExcel.getTemplateCode() == null || messageTemplateExcel.getTemplateName() == null ||
                        messageTemplateExcel.getTemplateTitle() == null || messageTemplateExcel.getTemplateContent() == null
                        || messageTemplateExcel.getIsEnabled() == null || messageTemplateExcel.getCreator() == null || messageTemplateExcel.getModifier() == null
                ) {
                    resultMap.setErrCode(1);
                    resultMap.setErrMsg("excel相关业务字段不可为空,请检查");
                    return resultMap;
                }
                messageTemplateExcel.setTenantCode(tenantCode);
            }
            resultMap = importExcelService.importMessageTemplateExcel(modelList);
        } catch (IOException e) {
            resultMap.setErrCode(1);
            resultMap.setErrMsg("IO异常，导入失败");
        }

        return resultMap;
    }

    @RequestMapping(value = "/outputMessageTemplateExcel", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "消息模板批量导出", httpMethod = "GET", notes = "消息模板批量导出")
    public void outputMessageTemplateExcel(HttpServletResponse response, @RequestParam("param") String param) {
        param = "(" + param + ")";
        try {
            String value = "attachment; filename=" + new String(
                    ("消息模板批量导出" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ExcelTypeEnum.XLSX.getValue()).getBytes("gb2312"), "ISO8859-1");
            List<MessageTemplateExcel> resList = outputExcelService.outputMessageTemplateExcel(param);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", value);
            EasyExcel.write(response.getOutputStream(), MessageTemplateExcel.class).sheet("消息模板数据").doWrite(resList);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/importBaseMessageSourceExcel", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "导入消息源", httpMethod = "POST", notes = "导入消息源")
    public ResultMap importBaseMessageSourceExcel(@RequestParam("excel") MultipartFile multipartFile, @RequestParam("tenantCode") String tenantCode) {
        ResultMap resultMap = new ResultMap();
        if (multipartFile == null || tenantCode == null) {
            resultMap.setErrCode(1);
            resultMap.setErrMsg("文件和tenantCode不可以为null");
            return resultMap;
        }
        ExcelReaderUtil<BaseMessageSourceExcel> excelReader = new ExcelReaderUtil<>(BaseMessageSourceExcel.class);
        List<BaseMessageSourceExcel> modelList;
        try {
            InputStream inputStream = multipartFile.getInputStream();
            modelList = excelReader.readByStream(inputStream);
            //数据校验
            for (BaseMessageSourceExcel excel : modelList) {
                //校验是否存在空字符串
                if (excel.getSourceCode() == null || excel.getSourceName() == null || excel.getSourceType() == null || excel.getSceneCode() == null
                        || excel.getSceneName() == null || excel.getSceneDescription() == null || excel.getHaveChannel() == null || excel.getHaveGroup() == null
                        || excel.getHaveTemplate() == null || excel.getIsEnabled() == null || excel.getCreator() == null || excel.getModifier() == null
                ) {
                    resultMap.setErrCode(1);
                    resultMap.setErrMsg("excel相关业务字段不可为空,请检查");
                    return resultMap;
                }
                //设置场景
                excel.setTenantCode(tenantCode);
            }
            resultMap = importExcelService.importBaseMessageSourceExcel(modelList);
        } catch (IOException e) {
            resultMap.setErrCode(1);
            resultMap.setErrMsg("IO异常，导入失败");
        }

        return resultMap;
    }

    @RequestMapping(value = "/outputBaseMessageSourceExcel", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "消息模板批量导出", httpMethod = "GET", notes = "消息模板批量导出")
    public void outputBaseMessageSourceExcel(HttpServletResponse response, @RequestParam("param") String param) {
        param = "(" + param + ")";
        String value = null;
        try {
            value = "attachment; filename=" + new String(
                    ("消息源批量导出" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ExcelTypeEnum.XLSX.getValue()).getBytes("gb2312"), "ISO8859-1");
            List<BaseMessageSourceExcel> resList = outputExcelService.outputBaseMessageSourceExcel(param);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", value);
            EasyExcel.write(response.getOutputStream(), BaseMessageSourceExcel.class).sheet("消息源数据").doWrite(resList);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/outputReceptGroupExcel", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "接受组批量导出", httpMethod = "GET", notes = "接受组批量导出")
    public void outputReceptGroupExcel(HttpServletResponse response, @RequestParam("param") String param) {
        BaseReceiveGroupQry baseReceiveGroupQry = new BaseReceiveGroupQry();
        param = "(" + param + ")";
        baseReceiveGroupQry.setParam(param);
        String value = null;
        try {
            value = "attachment; filename=" + new String(
                    ("接受组批量导出" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ExcelTypeEnum.XLSX.getValue()).getBytes("gb2312"), "ISO8859-1");
            PageInfo<BaseReceiveGroupDetailDTO> baseReceiveGroupDTOPageInfo = baseReceiveGroupService.page(baseReceiveGroupQry);
            List<BaseReceiveGroupDetailDTO> dtoList = baseReceiveGroupDTOPageInfo.getList();
            //excel无法转换list类型
            List<BaseReceiveGroupDetailExcel> resList = new ArrayList<>();
            for (BaseReceiveGroupDetailDTO detailDTO : dtoList) {
                String baseReceiveGroupRange = "";
                BaseReceiveGroupDetailExcel excel = new BaseReceiveGroupDetailExcel();
                BeanUtils.copyProperties(detailDTO, excel);
                List<BaseReceiveGroupRangeDTO> baseReceiveGroupRangeDTOList = detailDTO.getBaseReceiveGroupRangeDTOList();
                if (baseReceiveGroupRangeDTOList != null && baseReceiveGroupRangeDTOList.size() > 0) {
                    for (BaseReceiveGroupRangeDTO dto : baseReceiveGroupRangeDTOList) {
                        baseReceiveGroupRange = baseReceiveGroupRange + dto.getRangeEntityId().toString() + "";
                    }
                }
                excel.setBaseReceiveGroupRange(baseReceiveGroupRange);
                resList.add(excel);
            }
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", value);
            EasyExcel.write(response.getOutputStream(), BaseReceiveGroupDetailExcel.class).sheet("接受组数据").doWrite(resList);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/outputMsgSourceExcel", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "任务配置批量导出", httpMethod = "GET", notes = "任务配置批量导出")
    public void outputMsgSourceExcel(HttpServletResponse response, @RequestParam("param") String param) {
        MsgQuery msgQuery = new MsgQuery();
        param = "(" + param + ")";
        msgQuery.setParam(param);
        String value = null;
        try {
            value = "attachment; filename=" + new String(
                    ("任务配置批量导出" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ExcelTypeEnum.XLSX.getValue()).getBytes("gb2312"), "ISO8859-1");
            List<MsgSourceExcel> resList = new ArrayList<>();
            Page<MsgSourceVO> msgSourceVOPage = msgSourceService.listMsgSource(msgQuery);
            List<MsgSourceVO> msgSourceVOLsit = msgSourceVOPage.getResult();
            if (msgSourceVOLsit != null && msgSourceVOLsit.size() > 0) {
                for (MsgSourceVO vo : msgSourceVOLsit) {
                    MsgSourceExcel msgSourceExcel = new MsgSourceExcel();
                    String channelTypeListString = "";
                    String channelCodeListString = "";
                    String descriptionListString = "";
                    BeanUtils.copyProperties(vo, msgSourceExcel);
                    if (vo.getPushChannelList() != null && vo.getPushChannelList().size() > 0) {
                        for (PushChannelDto pushChannelDto : vo.getPushChannelList()) {
                            channelTypeListString = channelTypeListString + ChannelTypeEnum.getName(pushChannelDto.getChannelType()) + "\n";
                            channelCodeListString = channelCodeListString + pushChannelDto.getChannelCode() + "\n";
                            descriptionListString = descriptionListString + pushChannelDto.getDescription() + "\n";
                        }
                    }
                    msgSourceExcel.setChannelTypeListString(channelTypeListString);
                    msgSourceExcel.setDescriptionListString(descriptionListString);
                    msgSourceExcel.setChannelCodeListString(channelCodeListString);
                    resList.add(msgSourceExcel);
                }
            }
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", value);
            EasyExcel.write(response.getOutputStream(), MsgSourceExcel.class).sheet("任务配置批量导出").doWrite(resList);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
